package com.example.tools.security.holder;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.example.tools.security.component.UserDTO;
import io.micrometer.core.instrument.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: yang
 * @Date: 2021/8/22 0022 14:28
 * @Version 0.0.1
 */

@Component
public class LoginUserHolder implements LoginUserHolderService{

    @Autowired
    TokenStore tokenStore;

    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public UserDTO getCurrentUser(){
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("authorization");
        // OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        // Object credentials = oAuth2Authentication.getCredentials();
        // OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Authentication.getDetails();
        // String jwtToken = details.getTokenValue();
        String jwtToken  = token.replace("Bearer ","");

        Resource resource = new ClassPathResource("public.key");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }

        RsaVerifier rsaVerifier = new RsaVerifier(publicKey);
        Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
        String claims =  jwt.getClaims();

        JSONObject userJsonObject = new JSONObject(claims);
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(userJsonObject.getStr("user_name"));
        userDTO.setUid(Convert.toInt(userJsonObject.get("id")));
        userDTO.setRole(Convert.toList(String.class,userJsonObject.get("authorities")));
        return userDTO;
    }

}
